package com.fary.configweb;

import com.fary.controller.DemoMethodController;
import com.fary.converters.MyConverterFactory;
import com.fary.interceptor.MyInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.PathResource;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.*;

import java.io.IOException;
import java.util.function.Predicate;

@Import(WebMvcConfiguration.class)
@ComponentScan({"com.fary.controller","com.fary.configweb"})
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/views/", ".jsp");
    }

    /**
     * web容器添加转换器
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
//        registry.addConverter(new MyConverter());
        registry.addConverterFactory(new MyConverterFactory());
    }


    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.addPathPrefix("api", new Predicate<Class<?>>() {
            @Override
            public boolean test(Class<?> aClass) {
                return aClass == DemoMethodController.class;
            }
        });
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
    }

    @Bean
    public CommonsMultipartResolver multipartResolver(@Value("#{systemProperties['webapp.root']}") String webRoot) throws IOException {
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        // 设定默认编码
        commonsMultipartResolver.setDefaultEncoding("UTF-8");
        // 设定文件上传的最大值为5MB，5*1024*1024
        commonsMultipartResolver.setMaxUploadSize(5242880);
        // 设定文件上传时写入内存的最大值，如果小于这个参数不会生成临时文件，默认为10240
        commonsMultipartResolver.setMaxInMemorySize(40960);
        // 上传文件的临时路径
        commonsMultipartResolver.setUploadTempDir(new PathResource(webRoot + "upload"));
        // 延迟文件解析
        commonsMultipartResolver.setResolveLazily(true);
        return commonsMultipartResolver;
    }

}